from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.edge.service import Service
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager

def get_cookies(browser_type='chrome'):
    if browser_type == 'chrome':
        options = webdriver.ChromeOptions()
        driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
    elif browser_type == 'firefox':
        driver = webdriver.Firefox(service=Service(GeckoDriverManager().install()))
    elif browser_type == 'edge':
        driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install()))
    else:
        raise ValueError("Unsupported browser type. Choose from 'chrome', 'firefox', or 'edge'.")

    try:
        driver.get("https://www.goofish.com/")

        # Click on the login link
        WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.LINK_TEXT, "登录"))
        ).click()

        # Switch to the login iframe
        login_iframe = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "iframe#alibaba-login-box"))
        )
        driver.switch_to.frame(login_iframe)

        # Click on the keep login button
        button = WebDriverWait(driver, 300).until(
            EC.element_to_be_clickable(
                (By.CSS_SELECTOR, ".extra-login-content button[type='submit'].primary.keep-login-confirm-btn")
            )
        )
        button.click()

        # Switch back to the default content
        driver.switch_to.default_content()

        # Get cookies and format them
        cookies = driver.get_cookies()
        cookies_dict = {cookie["name"]: cookie["value"] for cookie in cookies}
        cookies_str = "; ".join([f"{k}={v}" for k, v in cookies_dict.items()])

        print("获取的 Cookie：", cookies_str)
        #driver.refresh()

    finally:
        driver.quit()

# Example usage
get_cookies(browser_type='chrome')
